// Import modules
const express = require('express')
const session = require('express-session')
const ioredis = require('ioredis')
const RedisStore = require('connect-redis')(session)
const mongoose = require('mongoose')

// Create App
const app = express()

// Redis Client
const client = ioredis.createClient(6379, process.env.REDIS_PORT_6379_TCP_ADDR)

// Compose Schema
const ComposeSchema = new mongoose.Schema({
  name:  String,
  build: String,
  ports: [String]
})

// Compose Model
const Compose = mongoose.model('Compose', ComposeSchema) 

// Create Session
app.use(session({
  store: new RedisStore({ client }),
  secret: 'Dream'
}))

// Routes for redis
app.get('/redis', (req, res) => {
  res.send('Redis is live!')
})
app.get('/redis/set', (req, res) => {
  client.set('key', 'Redis is live!');
  res.send(`It's redis.`)
})
app.get('/redis/get', (req, res) => {
  client.get('key').then(result => {
    res.send(result || 'Nothing!')
  })
})

// Routes for redis
app.get('/mongoose', (req, res) => {
  res.send('Mongoose is live!')
})
app.get('/mongoose/set', (req, res) => {
  var c = new Compose({
    name: 'docker',
    build: '.',
    ports: ['3000:3000']
  })

  c.save().then(() => {
      res.send(`It's mongoose.`);
    })
})
app.get('/mongoose/get', (req, res) => {
  Compose
    .find({ name: 'docker' })
    .then((result) => {
      res.send(result)
    })
})

app.use((req, res) => {
  res.send('Hello Docker, Express, Mongoose, Redis!')
})

mongoose.connect(`mongodb://${process.env.MONGO_PORT_27017_TCP_ADDR}`, (err) => {
  if (err) throw err

  // Start App
  app.listen(process.env.PORT || 3000)
})
